<template>
  <div class="app-container">
    <el-tabs v-model="editableTabsValue" type="border-card" @tab-remove="removeTab" style="padding: 30px 0;">
      <el-tab-pane
        label="缴费列表"
        name="缴费列表"
      >
        <br>
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
        > 
          <el-table-column align="center" label="序号" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="会员编号" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.patientCode }}
            </template>
          </el-table-column>
          <el-table-column label="姓名" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.patientName }}
            </template>
          </el-table-column>
          <el-table-column label="等级" width="80" align="center">
            <template slot-scope="scope">
              {{ scope.row.vipLevel }}
            </template>
          </el-table-column>
          <el-table-column label="就诊方式" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.typeName }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="就诊医生" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.doctorName }}
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="就诊科室" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.jobOfficeName }}
            </template>
          </el-table-column>
          <el-table-column label="就诊诊室" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.workAddressName }}
            </template>
          </el-table-column> -->
          <el-table-column label="就诊类型" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.visitType }}
            </template>
          </el-table-column>
          <el-table-column label="缴费内容" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.payContent }}
            </template>
          </el-table-column>
          <el-table-column label="卡状态" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.myCardList }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="挂号费(元)" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.registerPrice }}
            </template>
          </el-table-column> -->
          <el-table-column label="挂号时长" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.afterGuidanceTime }}
            </template>
          </el-table-column>
          <el-table-column label="缴费时长" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.waitPayTime }}
            </template>
          </el-table-column>
          <el-table-column label="就诊状态" width="150" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status | statusColorFilter">{{ scope.row.status | statusFilter }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="操作" align="center" width="400" >
            <template slot-scope="scope">
              <el-button type="primary" @click="optionPay(scope.row)">缴费操作</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="->, total, prev, pager, next"
          :total="this.total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="clickCurPage"
          >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
        :closable="item.isClose == true"
      >
        <!-- patient detail -->
        <div >
          <el-container>
            <el-main>
              <div>
                <div class="patient-base-info" style="font-size: 16px;top: 84px;height: 100px;line-height: 105px;"></div>
                <el-collapse class="patient-base-info" >
                  <el-collapse-item name="1">
                    <template slot="title">
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">基础信息: </span>
                          <span class="main-head-title">
                            {{item.content.code + ' '}}
                            {{item.content.name + ' '}}
                            {{item.content.sex + ' '}}
                            {{item.content.age + '周岁 /'}}
                            {{'手机尾号:'+ item.content.phone + ' /'}}
                            {{'身份证号:'+ item.content.idCard + ' /'}}
                            {{'出生日期:'+ item.content.birthday + ' '}}{{item.content.birthdayType | birthdayTypeFilter}}{{' /'}}
                            {{'会员等级:'}}{{item.content.vipLevel?item.content.vipLevel:'V0' }}
                          </span>
                        </el-col>
                      </el-row>
                    </template>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">就诊信息: </span>
                          <span class="main-head-title">
                            就诊信息内容
                          </span>
                          </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">卡券信息: </span>
                          <span class="main-head-title">卡券信息内容 </span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">用药信息: </span>
                          <span class="main-head-title">用药信息内容 </span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">预案信息: </span>
                          <span class="main-head-title">预案信息内容</span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">诊断信息: </span>
                          <span class="main-head-title">诊断信息内容</span>
                        </el-col>
                      </el-row>
                      <el-row :gutter=10>
                        <el-col :span=24>
                          <span class="main-head-title">就诊习惯: </span>
                          <span class="main-head-title">就诊习惯内容</span>
                        </el-col>
                      </el-row>
                  </el-collapse-item>
                </el-collapse>
              </div>
              <el-tabs v-model="item.content.patientTabsValue" type="border-card" closable @tab-remove="(targetName) => removePatientTab(targetName, item.content)">
                <el-tab-pane
                  v-for="patientTab in item.content.patientTabs"
                  :key="patientTab.name"
                  :label="patientTab.title"
                  :name="patientTab.name"
                >
                  <div v-if="item.content.patientTabsValue == '缴费处置'">
                    <el-collapse v-model="item.content.visitActiveName" >
                      <div class="activity-box">
                        <el-collapse value="1" style="width: 45%" >
                          <el-collapse-item name="1" >
                            <template slot="title">
                              <el-row :gutter=10>
                                <el-col :span=24>
                                  <span class="main-head-title">会员卡包</span>
                                </el-col>
                              </el-row>
                            </template>
                            <!-- 储值卡 -->
                            <el-row v-if="item.content.storedCard" :gutter=10>
                              <el-col :span=24>
                                <span class="main-head-title">{{'储值卡('}} {{ item.content.storedCard.status | cardStatusFilter  }} {{'), '}}</span>
                                <span class="main-head-title">
                                  余额： {{ item.content.storedCard.balance + ' 元 ' }}
                                </span>
                                </el-col>
                            </el-row>
                            <!-- 期限卡 -->
                            <el-row :gutter=10 v-if="item.content.limitTimeCardList && item.content.limitTimeCardList.length != 0" v-for="limitTimeCard in item.content.limitTimeCardList" :key="limitTimeCard.id">
                              <el-col :span=24>
                                <span class="main-head-title">{{'期限卡('}} {{ limitTimeCard.status | cardStatusFilter  }} {{'), '}} </span>
                                <span class="main-head-title">
                                  到期时间: {{ limitTimeCard.endTime }}
                                </span>
                                </el-col>
                            </el-row>
                            
                          </el-collapse-item>
                        </el-collapse>
                        
                        <el-collapse value="1" style="width: 45%" >
                          <el-collapse-item name="1" >
                            <template slot="title">
                              <el-row :gutter=10>
                                <el-col :span=24>
                                  <span class="main-head-title">活动</span>
                                </el-col>
                              </el-row>
                            </template>
                          </el-collapse-item>
                        </el-collapse>
                      </div>
                      <el-collapse-item name="办卡缴费">
                        <template #title>
                          <span style="font-size: 20px;font-weight: 600">办卡缴费</span>
                        </template>
                        <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.buyCardList"
                            element-loading-text="Loading"
                            border
                            fit
                            :header-cell-style="{ height: '5px', padding: '0 0' }"
                            :cell-style="{padding: '8px 0', height: '50px'}"
                          > 
                            <el-table-column label="序号" align="center" width="50">
                              <template slot-scope="subDrugScope">
                                <div>{{ subDrugScope.$index+1 }}</div>
                                <el-button v-if="subDrugScope.$index != item.content.buyCardList.length - 1 " class="del-btn"  type="danger" icon="el-icon-delete" circle @click="delDrug(subDrugScope.$index, item.content.buyCardList, item.content)"></el-button> 
                              </template>
                            </el-table-column>
                            <el-table-column :label="'卡券商品名称'" align="center" width="140">
                              <template slot-scope="subDrugScope">
                                <el-select size="mini" v-model="subDrugScope.row.id" placeholder="请选择" >
                                  <el-option
                                    v-for="card in item.content.cardList"
                                    :key="card.cardId"
                                    :label="card.cardName"
                                    :value="card.cardId"
                                    @click.native="selectCard(subDrugScope.row, card, item.content)"
                                    >
                                  </el-option>
                                </el-select>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'单价'" align="center" width="75" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.unitPrice }}
                              </template>
                            </el-table-column>
                            <el-table-column label="数量" align="center" width="90">
                              <template slot-scope="subDrugScope">
                                <el-input size= "mini" style="width: 60px" type="Number" min=1 placeholder="请输入" v-model="subDrugScope.row.realQuantity" @input="inputRealQuantity(subDrugScope.row)"></el-input>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'单品合计金额'" align="center" width="100" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.realSalePrice }}
                              </template>
                            </el-table-column>
                            <el-table-column :label="'备注'" align="center" width="140" >
                              <template slot-scope="subDrugScope">
                                <div class="first-row">
                                  <el-popover
                                    v-model="subDrugScope.row.visible"
                                    v-if = "subDrugScope.row.type == 2"
                                    placement="right"
                                    width="180"
                                    trigger="click"
                                    >
                                    <div class="drugs-item" >
                                      <div >开始日期</div>
                                      <el-date-picker 
                                        style="width: 150px;"
                                        size="mini"
                                        v-model="subDrugScope.row.startDate"
                                        >
                                      </el-date-picker>
                                    </div>
                                    <br>
                                    <br>
                                    <el-button type="primary" size="small" @click="changeStartDate(subDrugScope.row)" >确定</el-button>
                                    <el-button @click="subDrugScope.row.visible = false" size="small" >取消</el-button>
                                    
                                    <el-button slot="reference" size="mini">选择开卡日期</el-button>
                                  </el-popover>
                                </div>
                                <span class="second-row" style="left: 3px;" v-if="subDrugScope.row.type == 2" >{{ subDrugScope.row.startDateStr }}</span>

                              </template>
                            </el-table-column>
                            <el-table-column :label="'优惠力度'" align="center" width="200" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.discountStrength }}
                              </template>
                            </el-table-column>
                            <el-table-column :label="'说明'" align="center" width="200" >
                              <template slot-scope="subDrugScope">
                                <div v-if="subDrugScope.$index != item.content.buyCardList.length - 1 ">
                                  使用说明
                                  <el-tooltip style="margin: 5px;" :content="subDrugScope.row.description" effect="light" placement="top">
                                    <i class="el-icon-question"></i>
                                  </el-tooltip>
                                  办卡须知
                                  <el-tooltip style="margin: 5px;" :content="subDrugScope.row.cardDescription" effect="light" placement="top">
                                    <i class="el-icon-question"></i>
                                  </el-tooltip>
                                </div>
                              </template>
                            </el-table-column>
                          </el-table>

                          <!-- 办卡支付金额 -->
                        <el-divider content-position="left">办卡支付金额</el-divider>
                        <table style="width: 700px;">
                          <tr>
                            <!-- <th >产品</th>
                            <th >产品金额</th> -->
                            <th class="drug-payment-cell-1">办卡缴费</th>
                            <th style="text-align: left;">
                              应收金额 {{ item.content.payableAmountInfo.payableCardAmount  }}
                              <br>
                              已收金额 {{ item.content.cardPayInfo.planPaidCardAmount  }}
                                <span style="color: red;">{{ item.content.cardPayInfo.differCardAmount }}</span>
                              <br>
                              实收金额 {{ item.content.cardPayInfo.realPaidCardAmount }}
                            </th>
                          </tr>
                          <tr>
                              <!-- <th>卡</th>
                              <th>{{ item.content.payableAmountInfo.cardAmount ? item.content.payableAmountInfo.cardAmount : 0 }}</th> -->
                              <th>现金</th>
                              <td class="drug-payment-cell-2">
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.cashAmount" @input="inputPaidCardAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <!-- <th></th>
                              <th></th> -->
                              <th>微信</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.wechatAmount" @input="inputPaidCardAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <!-- <th></th>
                              <th></th> -->
                              <th>支付宝</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.alipayAmount" @input="inputPaidCardAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <!-- <th></th>
                              <th></th> -->
                              <th>外协卡</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.outCardAmount" @input="inputPaidCardAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <!-- <th></th>
                              <th></th> -->
                              <th>欠款</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.debtAmount" @input="inputPaidCardAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                          </tr>
                          <tr>
                              <!-- <th></th>
                              <th></th> -->
                              <th>免费</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.cardPayInfo.freeAmount" @input="inputPaidCardAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                              <th class="drug-payment-cell-3">原因</th>
                              <td>                                
                                <el-input style="width: 200px;" size="mini" placeholder="请输入原因" v-model="item.content.cardPayInfo.remark" >
                                </el-input>
                              </td>
                          </tr>
                        </table>
                        <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                          <el-button type="primary" @click="confirmCard(item.content)" :disabled="item.content.status == GuidanceStatusEnum.DONE || item.content.status == GuidanceStatusEnum.SUSPEND">办卡提交</el-button>
                        </div>
                      </el-collapse-item>

                      <el-collapse-item  name="处方缴费">
                        <template #title>
                          <span style="font-size: 20px;font-weight: 600">处方缴费</span>
                        </template>
                        
                        <!-- 处方支付金额 -->
                        <el-divider content-position="left">处方支付金额</el-divider>
                        <div style=" display: flex;justify-content: flex-start;">

                          <table style="margin-right: 100px;width: 250px;">
                            <tr>
                              <th >缴费类别</th>
                              <th style="width: 150px;">
                                应收金额 
                                <el-button style="display: inline;margin-left: 10px;" type="primary" size="mini" @click="payableInfoDialog(item.content)" >详情</el-button>
                              </th>
                            </tr>
                            <tr>
                              <th>分装商品</th>
                              <th>{{ item.content.payableAmountInfo.subPackageAmount }}</th>
                            </tr>
                            <tr>
                              <th>整装商品</th>
                              <th>{{ item.content.payableAmountInfo.packageAmount }}</th>
                            </tr>
                            <tr>
                              <th>检查</th>
                              <th>{{ item.content.payableAmountInfo.inspectionAmount }}</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                          </table>
                          <table style="width: 900px;">
                            <tr>
                              <th >商品缴费</th>
                              <th style="text-align: left;">
                                应收金额 {{ item.content.payableAmountInfo.payableDrugAmount  }}
                                <br>
                                已收金额 {{ item.content.drugPayInfo.planPaidDrugAmount  }}
                                  <span style="color: red;">{{ item.content.drugPayInfo.differDrugAmount }}</span>
                                <br>
                                实收金额 {{ item.content.drugPayInfo.realPaidDrugAmount }}
                              </th>
                            </tr>
                            <tr>
                              <th>活动</th>
                              <th>
                                
                              </th>
                            </tr>
                            <tr>
                              <th>券</th>
                              <th>
                                
                              </th>
                            </tr>
                            <tr>
                              <th class="drug-payment-cell-1">储值卡</th>
                              <td class="drug-payment-cell-2">
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.storedCardAmount" @input="inputPaidDrugAmount(item.content)" :disabled="item.content.drugPayInfo.storedCardDisabled">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                              <th>
                                <tr>
                                  <th class="drug-payment-cell-3">持卡人编号/姓名</th>
                                  <td class="drug-payment-cell-4">
                                    <el-select v-model="item.content.drugPayInfo.patientCardId" filterable placeholder="持卡人编号">
                                      <el-option
                                        v-for="patientCardItem in patientCardEnum"
                                        :key="patientCardItem.id"
                                        :label="patientCardItem.patientCode + ' - ' + patientCardItem.patientName"
                                        :value="patientCardItem.id"
                                        @click.native="selectPatientCard(patientCardItem, item.content)"
                                        >
                                      </el-option>
                                    </el-select>
                                  </td>
                                </tr>
                                <tr>
                                  <th class="drug-payment-cell-3">使用前金额</th>
                                  <th class="drug-payment-cell-4">{{ item.content.drugPayInfo.beforeAmount }}</th>
                                  <th class="drug-payment-cell-5">使用后余额</th>
                                  <th class="drug-payment-cell-6">{{ item.content.drugPayInfo.afterAmount }}</th>
                                </tr>
                              </th>
                            </tr>
                            <tr>
                              <th colspan="4" class="card-payment-description">自费部分:{{ item.content.drugPayInfo.storedCardPatientAmount }}元, 优惠部分：{{ item.content.drugPayInfo.storedCardFreeAmount }}</th>
                            </tr>
                            <tr>
                              <th>期限卡</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 v-model="item.content.drugPayInfo.limitCardFreeAmount" :disabled="true">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                              <th>
                                <tr>
                                  <th class="drug-payment-cell-3">使用天数</th>
                                  <th class="drug-payment-cell-4">{{ item.content.drugPayInfo.limitCardUsedDays }}</th>
                                  <th class="drug-payment-cell-5">剩余天数</th>
                                  <th class="drug-payment-cell-6">{{ item.content.drugPayInfo.limitCardResidueDays }}</th>
                                </tr>
                              </th>
                            </tr>
                            <tr>
                              <th colspan="4" class="card-payment-description">自费部分:0元, 优惠部分：{{ item.content.drugPayInfo.limitCardFreeAmount }}</th>
                            </tr>
                            <tr>
                              <th>现金</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.cashAmount" @input="inputPaidDrugAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                            </tr>
                            <tr>
                              <th>微信</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.wechatAmount" @input="inputPaidDrugAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                            </tr>
                            <tr>
                              <th>支付宝</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.alipayAmount" @input="inputPaidDrugAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                            </tr>
                            <tr>
                              <th>外协卡</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.outCardAmount" @input="inputPaidDrugAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                            </tr>
                            <tr>
                              <th>欠款</th>
                              <td>
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.debtAmount" @input="inputPaidDrugAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                            </tr>
                            <tr>
                              <th class="drug-payment-cell-1">免费</th>
                              <td class="drug-payment-cell-2">
                                <el-input style="width: 140px;" size="mini" type="Number" min=0 placeholder="请输入" v-model="item.content.drugPayInfo.freeAmount" @input="inputPaidDrugAmount(item.content)">
                                  <template slot="append">
                                    <span style="font-size: 14px">元</span>
                                  </template>
                                </el-input>
                              </td>
                              <th>
                                <tr>
                                  <th class="drug-payment-cell-3">原因</th>
                                  <td class="drug-payment-cell-4">                                
                                    <el-input style="width: 200px;" size="mini" placeholder="请输入原因" v-model="item.content.drugPayInfo.remark" >
                                    </el-input>
                                  </td>
                                </tr>
                              </th>
                            </tr>
                          </table>
                        </div>
                        <!-- <table>
                          <tr>
                            <th >商品应收合计：</th>
                            <th >
                              {{ item.content.payableAmountInfo.payableDrugAmount }}
                              {{  '+ (期限卡减免' + item.content.drugPayInfo.limitCardFreeAmount + ')' }}
                            </th>
                          </tr>
                          <tr>
                            <th >商品实收合计：</th>
                            <th >
                              {{ item.content.drugPayInfo.realPaidDrugAmount }}<br/>
                              {{ '(储值卡支付' + item.content.drugPayInfo.storedCardAmount + ')' }}<br/>
                              {{ '(现场支付' }}
                              {{ (Number(item.content.drugPayInfo.realPaidDrugAmount) - Number(item.content.drugPayInfo.storedCardAmount)).toFixed(2) + ')' }}
                            </th>
                          </tr>
                        </table> -->
                        <!-- 汇总 -->
                        <el-divider content-position="left">汇总</el-divider>
                        <div style="display:flex;justify-content: flex-start;">
                          <table style="margin-right: 100px;width: 250px;">
                            <tr>
                              <th colspan="2">消费汇总</th>
                            </tr>
                            <tr>
                              <th >办卡金额</th>
                              <th >{{ Number(item.content.payableAmountInfo.payableCardAmount) }}</th>
                            </tr>
                            <tr>
                              <th >商品金额</th>
                              <th >
                                  {{ Number(item.content.payableAmountInfo.payableDrugAmount) }}
                                  <!-- {{ Number(item.content.cardPayInfo.realPaidCardAmount) + Number(item.content.drugPayInfo.realPaidDrugAmount) - Number(item.content.drugPayInfo.storedCardAmount) }}
                                  {{ ' (储值卡支付' + item.content.drugPayInfo.storedCardAmount + ')' }} -->
                              </th>
                            </tr>
                            <tr>
                              <th >合计</th>
                              <th >
                                  {{ Number(item.content.payableAmountInfo.payableCardAmount) + Number(item.content.payableAmountInfo.payableDrugAmount) }}
                                  <!-- {{ Number(item.content.cardPayInfo.realPaidCardAmount) + Number(item.content.drugPayInfo.realPaidDrugAmount) - Number(item.content.drugPayInfo.storedCardAmount) }}
                                  {{ ' (储值卡支付' + item.content.drugPayInfo.storedCardAmount + ')' }} -->
                              </th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                            <tr class="table-separate">
                              <th>透明占位</th>
                              <th>透明占位</th>
                            </tr>
                          </table>
                          <table style="width: 900px;">
                            <tr>
                              <th colspan="2">缴费汇总</th>
                            </tr>
                            <tr>
                              <th>活动</th>
                              <th>
                                
                              </th>
                            </tr>
                            <tr>
                              <th>券</th>
                              <th>
                                
                              </th>
                            </tr>
                            <tr>
                              <th class="drug-payment-cell-1">储值卡</th>
                              <th class="drug-payment-cell-2">
                                {{ item.content.drugPayInfo.storedCardAmount }}
                              </th>
                              <th>
                                <tr>
                                  <th class="drug-payment-cell-3">持卡人编号/姓名</th>
                                  <th class="drug-payment-cell-4">
                                    <el-select v-model="item.content.drugPayInfo.patientCardId" filterable placeholder="持卡人编号" :disabled="true">
                                      <el-option
                                        v-for="patientCardItem in patientCardEnum"
                                        :key="patientCardItem.id"
                                        :label="patientCardItem.patientCode + ' - ' + patientCardItem.patientName"
                                        :value="patientCardItem.id"
                                        >
                                      </el-option>
                                    </el-select>
                                  </th>
                                </tr>
                                <tr>
                                  <th class="drug-payment-cell-3">使用前金额</th>
                                  <th class="drug-payment-cell-4">{{ item.content.drugPayInfo.beforeAmount }}</th>
                                  <th class="drug-payment-cell-5">使用后余额</th>
                                  <th class="drug-payment-cell-6">{{ item.content.drugPayInfo.afterAmount }}</th>
                                </tr>
                              </th>
                            </tr>
                            <tr>
                              <th colspan="4" class="card-payment-description">自费部分:{{ item.content.drugPayInfo.storedCardPatientAmount }}元, 优惠部分：{{ item.content.drugPayInfo.storedCardFreeAmount }}</th>
                            </tr>
                            <tr>
                              <th>期限卡</th>
                              <th>
                                {{ item.content.drugPayInfo.limitCardFreeAmount }}
                              </th>
                              <th>
                                <tr>
                                  <th class="drug-payment-cell-3">使用天数</th>
                                  <th class="drug-payment-cell-4">{{ item.content.drugPayInfo.limitCardUsedDays }}</th>
                                  <th class="drug-payment-cell-5">剩余天数</th>
                                  <th class="drug-payment-cell-6">{{ item.content.drugPayInfo.limitCardResidueDays }}</th>
                                </tr>
                              </th>
                              
                            </tr>
                            <tr>
                              <th colspan="4" class="card-payment-description">自费部分:0元, 优惠部分：{{ item.content.drugPayInfo.limitCardFreeAmount }}</th>
                            </tr>
                            <tr>
                              <th>现金</th>
                              <th>{{ Number(item.content.cardPayInfo.cashAmount) + Number(item.content.drugPayInfo.cashAmount) }}</th>
                            </tr>
                            <tr>
                              <th>微信</th>
                              <th>{{ Number(item.content.cardPayInfo.wechatAmount) + Number(item.content.drugPayInfo.wechatAmount) }}</th>
                            </tr>
                            <tr>
                              <th>支付宝</th>
                              <th>{{ Number(item.content.cardPayInfo.alipayAmount) + Number(item.content.drugPayInfo.alipayAmount) }}</th>
                            </tr>
                            <tr>
                              <th>外协卡</th>
                              <th>{{ Number(item.content.cardPayInfo.outCardAmount) + Number(item.content.drugPayInfo.outCardAmount) }}</th>
                            </tr>
                            <tr>
                              <th>欠款</th>
                              <th>{{ Number(item.content.cardPayInfo.debtAmount) + Number(item.content.drugPayInfo.debtAmount) }}</th>
                            </tr>
                            <tr>
                              <th class="drug-payment-cell-1">免费</th>
                              <th>{{ Number(item.content.cardPayInfo.freeAmount) + Number(item.content.drugPayInfo.freeAmount) }}</th>
                              <th>
                                <tr>
                                  <th class="drug-payment-cell-3">原因</th>
                                  <th class="drug-payment-cell-4">{{ item.content.drugPayInfo.remark }}</th>
                                </tr>
                              </th>
                            </tr>
                            <tr>
                              <th colspan="4" class="card-payment-description">本次消费共节省{{ Number(item.content.drugPayInfo.storedCardFreeAmount) + Number(item.content.drugPayInfo.limitCardFreeAmount) }}元</th>
                            </tr>
                          </table>
                          <!-- <table>
                            <tr>
                              <th >消费汇总</th>
                            </tr>
                            <tr>
                                <th>卡</th>
                                <th>{{ item.content.drugPayInfo.storedCardAmount }}</th>
                            </tr>
                            <tr>
                                <th>现金</th>
                                <th>{{ Number(item.content.cardPayInfo.cashAmount) + Number(item.content.drugPayInfo.cashAmount) }}</th>
                            </tr>
                            <tr>
                                <th>微信</th>
                                <th>{{ Number(item.content.cardPayInfo.wechatAmount) + Number(item.content.drugPayInfo.wechatAmount) }}</th>
                            </tr>
                            <tr>
                                <th>支付宝</th>
                                <th>{{ Number(item.content.cardPayInfo.alipayAmount) + Number(item.content.drugPayInfo.alipayAmount) }}</th>
                            </tr>
                            <tr>
                                <th>外协卡</th>
                                <th>{{ Number(item.content.cardPayInfo.outCardAmount) + Number(item.content.drugPayInfo.outCardAmount) }}</th>
                            </tr>
                            <tr>
                                <th>欠款</th>
                                <th>{{ Number(item.content.cardPayInfo.debtAmount) + Number(item.content.drugPayInfo.debtAmount) }}</th>
                            </tr>
                            <tr>
                                <th>免费</th>
                                <th>{{ Number(item.content.cardPayInfo.freeAmount) + Number(item.content.drugPayInfo.freeAmount) }}</th>
                            </tr>
                          </table> -->
                        </div>
                        <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                          <el-button type="primary" @click="confirmPaid(item.content)" :disabled="item.content.status == GuidanceStatusEnum.DONE || item.content.status == GuidanceStatusEnum.SUSPEND">缴费提交</el-button>
                        </div>
                      </el-collapse-item>
                    </el-collapse>
                  </div>
                </el-tab-pane>
              </el-tabs>

            </el-main>
            <el-aside width="220px">
              <el-menu
                @select="(key, keyPath) => handleMenuSelect(key, keyPath, item.content)" 
                default-active="2"
                :default-openeds="defaultOpen"
                class="el-menu-vertical-demo"
                @open="handleOpen"
                @close="handleClose">
                <el-submenu index="会员管理" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">会员管理</span>
                  </template>
                    <el-menu-item index="会员基础信息查询" style="font-size: 14px">会员基础信息查询</el-menu-item>
                </el-submenu>
                <el-submenu index="缴费处置" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">缴费处置</span>
                  </template>
                    <el-menu-item index="办卡" style="font-size: 14px">办卡</el-menu-item>
                    <el-menu-item index="缴费" style="font-size: 14px">缴费</el-menu-item>
                </el-submenu>
                <el-submenu index="会员就诊记录查询" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">会员就诊记录查询</span>
                  </template>
                    <el-menu-item index="会员就诊记录查询" style="font-size: 14px">会员就诊记录查询</el-menu-item>
                </el-submenu>
                <el-submenu index="缴费/卡/券" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">缴费/卡/券</span>
                  </template>
                    <el-menu-item index="会员缴费/卡/券记录查询" style="font-size: 14px">会员缴费/卡/券记录查询</el-menu-item>
                </el-submenu>
                <el-submenu index="租借药盒" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">租借药盒</span>
                  </template>
                    <el-menu-item index="会员租借药盒记录查询" style="font-size: 14px">会员租借药盒记录查询</el-menu-item>
                </el-submenu>
              </el-menu>
            </el-aside>
          </el-container>
        </div>

      </el-tab-pane>
    </el-tabs>
    <el-dialog title="消费详情" :visible.sync="payableInfoVisible" >
      <!-- 分装药品 -->
      <el-divider content-position="left"><b>分装药品</b></el-divider>
      <el-table :data="dialogPayableInfo.subPackagePendingList" border>
        <el-table-column property="date" label="名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.code + '[' +scope.row.commonName + ']'}}</span><br>
            <span>{{ scope.row.name }}</span><br>
            <span>{{ scope.row.specs }}</span>
          </template>
        </el-table-column>
        <el-table-column property="unitPrice" label="单价" align="center"></el-table-column>
        <el-table-column property="realQuantity" label="数量" align="center"></el-table-column>
        <el-table-column property="realSalePrice" label="金额" align="center"></el-table-column>
      </el-table>
      <br>
      <!-- 整装药品 -->
      <el-divider content-position="left"><b>整装药品</b></el-divider>
      <el-table :data="dialogPayableInfo.packagePendingList" border>
        <el-table-column property="date" label="名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.code + '[' +scope.row.commonName + ']'}}</span><br>
            <span>{{ scope.row.name }}</span><br>
            <span>{{ scope.row.specs }}</span>
          </template>
        </el-table-column>
        <el-table-column property="unitPrice" label="单价" align="center"></el-table-column>
        <el-table-column property="realQuantity" label="数量" align="center"></el-table-column>
        <el-table-column property="realSalePrice" label="金额" align="center"></el-table-column>
        <el-table-column property="remark" label="备注" align="center"></el-table-column>
      </el-table>
      <br>
      <!-- 实验室检查项 -->
      <el-divider content-position="left"><b>实验室检查项</b></el-divider>
      <el-table :data="dialogPayableInfo.inspectionPendingList" border>
        <el-table-column property="date" label="名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.code + '[' +scope.row.commonName + ']'}}</span><br>
            <span>{{ scope.row.name }}</span><br>
            <span>{{ scope.row.specs }}</span>
          </template>
        </el-table-column>
        <el-table-column property="unitPrice" label="单价" align="center"></el-table-column>
        <el-table-column property="realQuantity" label="数量" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.operation | operationFilter }}</span><br>
          </template>
        </el-table-column>
        <el-table-column label="使用节点" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.operationStep | operationStepFilter }}</span><br>
          </template>
        </el-table-column>
        <el-table-column property="realQuantity" label="金额" align="center">
          <template slot-scope="scope">
            {{ scope.row.unitPrice * scope.row.realQuantity }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelInfo">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script>

import { getList } from '@/api/guidance'
import { getList as getPatientList} from '@/api/patient'
import { GuidanceStatusEnum } from '@/enums/guidanceStatusEnum'
import { CardEnum } from '@/enums/CardEnum.js'
import { getList as getCardList } from '@/api/card'
import { getList as getMyCardList, add as addUserCard, getAllStoredCardList } from '@/api/patientCard'
import { getVisitAmount, add as addPaid } from '@/api/paid'
import { dateToString, addDate } from '../../utils/dateUtil'
import Decimal from 'decimal.js';

export default {
  name: "Paid",
  filters: {
    statusColorFilter(status) {
      const statusMap = ['', '', '', '', '', 'success', 'info']
      return statusMap[status]
    },
    birthdayTypeFilter(status) {
      const statusMap = ['', '阳', '阴']
      return statusMap[status]
    },
    statusFilter(status) {
      const statusMap = ['候诊', '就诊中', '待检查', '待缴费', '待取药', '待检查/待取药', '已完成', '中止']
      return statusMap[status]
    },
    cardStatusFilter(status) {
      const statusMap = ['未开通', '可用', '不可用']
      return statusMap[status]
    },
    operationFilter(operation) {
      const statusMap = ['', '选择操作', '不选择操作', '缴费预存']
      return statusMap[operation]
    },
    operationStepFilter(operationStep) {
      const statusMap = ['', '诊中', '诊后']
      return statusMap[operationStep]
    }
  },
  data() {
    const validateSource = (rule, value, callback) => {
      if (!value) callback(new Error('请输入名称')) 
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      info: {},
      form: {},
      dialogTitle: '添加来源',
      depts:[],
      formRules: {
        source: [{ required: true, trigger: 'blur', validator: validateSource }],
      },
      editableTabsValue: '缴费列表',
      editableTabs: [],
      defaultOpen: ['会员管理', '诊中处置', '会员就诊记录查询', '缴费/卡/券', '租借药盒'],
      patientCardEnum: [],
      payableInfoVisible: false,
      dialogPayableInfo: {},
      GuidanceStatusEnum: GuidanceStatusEnum
    }
  },
  created() {
    this.fetchData()
    this.startInterval()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      this.initListData()
    },
    initListData() {
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var deptId = loginInfo.loginDept.deptId
      var jobOfficeId = loginInfo.loginJobOffice?loginInfo.loginJobOffice.jobOfficeId:undefined
      this.$set(this, 'listLoading', true)
      getList({currentPage: this.currentPage, pageSize: this.pageSize, deptId: deptId, jobOfficeId: jobOfficeId, status: GuidanceStatusEnum.PAYING}).then(res=>{
        console.log(res.data)
        this.list = res.data.records
        this.$set(this, 'total', res.data.total)
        this.noMasterDoctorNum = this.list.filter(item=> !item.doctorId).length
        this.doneWaitingNum = this.list.filter(item=> item.remainderTime == 0).length
        this.noInspectionNum = this.list.filter(item=> !item.masterDoctor).length
        this.noCheckNum = this.list.filter(item=> !item.masterDoctor).length
        this.noInfoNum = this.list.filter(item=> !item.masterDoctor).length
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
    },
    startInterval() {
      this.intervalId = setInterval(this.callApi, 1000 * 60);
    },
    stopInterval() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
    },
    callApi() {
      // 调用接口的逻辑
      console.log('刷新缴费列表');
      this.initListData()
    },
    clickCurPage(val){
      this.currentPage = val
      this.initListData()
    },
    optionPay(visit) {
      getPatientList({name: visit.patientCode, currentPage: 1, pageSize: 1}).then(res=> {
        console.log("get patient list res===>", res)
        var patient = res.data.records[0]
        patient.guidanceCode = visit.guidanceCode
        patient.status = visit.status
        var list = this.editableTabs.filter(item => item.name == patient.code)
        this.initPatientVisitData(patient, list)
      })
    },
    async initPatientVisitData(patient, list) {
      if(list.length != 0) {
        this.editableTabsValue = patient.code
        return
      }
      this.$set(patient, 'patientTabsValue', '缴费处置')
      this.$set(patient, 'patientTabs', [{
        title: '缴费处置',
        name: '缴费处置',
        content: {}
      }])
      
      this.$set(patient, 'visitActiveName', '办卡')
      // 获取卡列表
      const cardListRes = await getCardList()
      console.log('cardListRes.data', cardListRes.data)
      this.$set(patient, 'cardList', cardListRes.data)
      // 初始化支付对象
      // 应收
      this.$set(patient, 'payableAmountInfo', {cardAmount: 0, subPackageAmount: 0, packageAmount: 0, inspectionAmount: 0, payableCardAmount: 0, payableDrugAmount: 0})
      // 实收
      this.$set(patient, 'cardPayInfo', {cashAmount: 0, wechatAmount: 0, alipayAmount: 0, outCardAmount: 0, debtAmount: 0, freeAmount: 0, realPaidCardAmount: 0, planPaidCardAmount: 0})
      this.$set(patient, 'drugPayInfo', {limitCardFreeAmount: 0, storedCardAmount: 0, cashAmount: 0, wechatAmount: 0, alipayAmount: 0, outCardAmount: 0, debtAmount: 0, freeAmount: 0, realPaidDrugAmount: 0, planPaidDrugAmount: 0, differDrugAmount: '',  storedCardDisabled: true, storedCardPatientAmount: 0, storedCardFreeAmount: 0})
      // 初始化所有会员的卡
      const allStoredCardListRes = await getAllStoredCardList()
      this.patientCardEnum = allStoredCardListRes.data

      const myCardListRes = await getMyCardList({patientId: patient.id})
      console.log('myCardListRes', myCardListRes)
      this.$set(patient, 'buyCardList', [{}])
      // 期限卡可以办理多个
      const limitTimeCardList = myCardListRes.data.filter(myCard => myCard.cardType == CardEnum.LIMIT_DATE_CARD)
      this.$set(patient, 'limitTimeCardList', limitTimeCardList)
      // 储值卡每个用户只有一个
      const storedCardList = myCardListRes.data.filter(myCard => myCard.cardType == CardEnum.STORED_CARD)
      this.$set(patient, 'storedCard', storedCardList[0])
      // 需缴费金额
      getVisitAmount({guidanceCode: patient.guidanceCode, patientId: patient.id}).then(res=> {
        console.log('visitRes', res)
        this.$set(patient.payableAmountInfo, 'cardAmount', res.data.cardAmount)
        this.$set(patient.drugPayInfo, 'limitCardFreeAmount', res.data.limitCardFreeAmount)
        this.$set(patient.drugPayInfo, 'limitCardUsedDays', res.data.limitCardUsedDays)
        this.$set(patient.drugPayInfo, 'limitCardResidueDays', res.data.limitCardResidueDays)
        this.$set(patient.payableAmountInfo, 'subPackageAmount', res.data.subPackageDrugAmount)
        this.$set(patient.payableAmountInfo, 'packageAmount', res.data.packageDrugAmount)
        this.$set(patient.payableAmountInfo, 'inspectionAmount', res.data.inspectionAmount)
        this.$set(patient.payableAmountInfo, 'payableCardAmount', res.data.cardAmount)
        this.$set(patient.payableAmountInfo, 'payableDrugAmount', new Decimal(res.data.inspectionAmount).plus(new Decimal(res.data.packageDrugAmount)).plus(new Decimal(res.data.subPackageDrugAmount)).toNumber())
        this.$set(patient.payableAmountInfo, 'inspectionPendingList', res.data.inspectionPendingList)
        this.$set(patient.payableAmountInfo, 'subPackagePendingList', res.data.subPackagePendingList)
        this.$set(patient.payableAmountInfo, 'packagePendingList', res.data.packagePendingList)
        // 计算相差多少钱（红字）
        this.calculateDrugDiffAmount(patient)
      })

      this.editableTabs.push({
        title: patient.name,
        name: patient.code,
        content: patient,
        isClose: true
      })
      this.editableTabsValue = patient.code
    },
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      if(this.editableTabs.length == 0) this.editableTabsValue = '缴费列表'
    },
    /** patient detail page function */
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    handleMenuSelect(key, keyPath, patient) {
      console.log(keyPath)
      var tabValue = keyPath[0]
      console.log(tabValue)
      this.$set(patient, 'visitActiveName', keyPath[1])
      var list = patient.patientTabs.filter(item => item.name == tabValue)
      if(list.length != 0) {
        patient.patientTabsValue = tabValue
        return
      }
      

      patient.patientTabs.push({
        title: tabValue,
        name: tabValue,
        content: {}
      })
      patient.patientTabsValue = tabValue
    },
    delDrug(index, list, patient) {
      const card = list[index]
      this.$confirm('删除 '+ card.name + ' x ' + card.realQuantity + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        list.splice(index, 1)
        // 删除要 重新计算支付金额
        this.calculatePayableCardAmount(patient)

        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
    },
    selectCard(curCard, cardRecord, patient) {
      console.log('patient--', patient)
      const rule = JSON.parse(cardRecord.rule)
      console.log('rule--', rule)
      // 如果是修改则不加一行
      if(!curCard.unitPrice) {
        patient.buyCardList.push({})
      }
      this.$set(curCard, 'type', cardRecord.type)
      this.$set(curCard, 'rule', cardRecord.rule)
      this.$set(curCard, 'unitPrice', rule.amount)
      this.$set(curCard, 'name', cardRecord.name)
      this.$set(curCard, 'realQuantity', 1)
      this.$set(curCard, 'realSalePrice', rule.amount)
      this.$set(curCard, 'discountStrength', cardRecord.discountStrength)
      this.$set(curCard, 'description', cardRecord.description)
      this.$set(curCard, 'cardDescription', cardRecord.cardDescription)
      // 累加办卡需支付金额
      this.calculatePayableCardAmount(patient)
      // 计算相差多少钱（红字）
      this.calculateCardDiffAmount(patient)
    },
    calculatePayableCardAmount(patient) {
      let totalAmount = new Decimal(0)
      for (let index = 0; index < patient.buyCardList.length-1; index++) {
        var element = patient.buyCardList[index]
        totalAmount = totalAmount.plus(new Decimal(element.unitPrice).mul(new Decimal(element.realQuantity)))
        console.log('payableCardAmount', totalAmount.toNumber())
      }
      this.$set(patient.payableAmountInfo, 'payableCardAmount', totalAmount.toNumber())
    },
    inputRealQuantity(row) {
      if(row.realQuantity > 99) this.$set(row, 'realQuantity', 0)
      this.checkNumInput(row, 'realQuantity', row.realQuantity)
      this.$set(row, 'realSalePrice', (row.realQuantity * row.unitPrice).toFixed(2))
    },
    checkNumInput(obj, prop, content) {
      // 判空
      if(!content) this.$set(obj, prop, 0)
      // 删除0开头
      this.$set(obj, prop, Number(content))
      // 负数时改为0
      if(!content) this.$set(obj, prop, 0)
    },
    async confirmCard(patient) {
      console.log('confirm patient', patient)
      // 办卡
      console.log('guidance.buyCardList', patient.buyCardList)
      this.$confirm('确定办理', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const reqBuyCardList = JSON.parse(JSON.stringify(patient.buyCardList.slice(0, -1)))  // 入参将最后一个添加行数据截掉
        if(!this.checkCardConfirm(reqBuyCardList, patient)) return
        for (const element of reqBuyCardList) {
          element.cardId = element.id
          element.cardName = element.name
          element.cardRule = element.rule
          element.cardType = element.type
          element.status = 0
        }
        const reqDto = {
          patientId: patient.id, 
          userCardList: reqBuyCardList,
          payableAmountInfo: patient.payableAmountInfo,
          cardPayInfo: patient.cardPayInfo,
          paidCardTotalAmount: patient.payableAmountInfo.payableCardAmount,
        }
        const res = await addUserCard(reqDto)
        console.log('add userCardRes', res)
        const myCardListRes = await getMyCardList({patientId: patient.id})
        console.log('myCardListRes', myCardListRes)
        // 期限卡可以办理多个
        const limitTimeCardList = myCardListRes.data.filter(myCard => myCard.cardType == CardEnum.LIMIT_DATE_CARD)
        this.$set(patient, 'limitTimeCardList', limitTimeCardList)
        // 储值卡每个用户只有一个
        const storedCardList = myCardListRes.data.filter(myCard => myCard.cardType == CardEnum.STORED_CARD)
        this.$set(patient, 'storedCard', storedCardList[0])
        // 提交办卡后，重新获取需缴费金额
        getVisitAmount({guidanceCode: patient.guidanceCode, patientId: patient.id}).then(res=> {
          console.log(res)
          this.$set(patient.payableAmountInfo, 'cardAmount', res.data.cardAmount)
          this.$set(patient.payableAmountInfo, 'limitCardFreeAmount', res.data.limitCardFreeAmount)
          this.$set(patient.payableAmountInfo, 'subPackageAmount', res.data.subPackageDrugAmount)
          this.$set(patient.payableAmountInfo, 'packageAmount', res.data.packageDrugAmount)
          this.$set(patient.payableAmountInfo, 'inspectionAmount', res.data.inspectionAmount)
        })
        this.$message({
          type: 'success',
          message: '办理成功!'
        });
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    checkCardConfirm(buyCardList, patient) {
      for (const buyCard of buyCardList) {
        if(buyCard.unitPrice) {
          if(!buyCard.realQuantity || buyCard.realQuantity == 0) {
            this.$alert('请填写' + buyCard.name + '数量', '错误', {
              confirmButtonText: '确定',
              type: 'error',
            });
            return false
          }
          if(buyCard.type == 2) {
            if(!buyCard.startDate) {
              this.$alert('请选择' + buyCard.name + '开始日期', '错误', {
                confirmButtonText: '确定',
                type: 'error',
              });
              return false
            }
          }
        }
      }
      // 校验支付金额输入是否正确
      if (Number(patient.payableAmountInfo.payableCardAmount) != Number(patient.cardPayInfo.planPaidCardAmount)) {
        this.$alert('办卡金额输入有误', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return false
      }
      if(Number(patient.cardPayInfo.freeAmount) != 0 && (!patient.cardPayInfo.remark || patient.cardPayInfo.remark.trim() == '')) {
        this.$alert('免费金额必须填写原因', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return false
      }
      return true
    },
    async confirmPaid(patient) {
      // 缴费
      if(!this.checkDrugPaid(patient)) return
      console.log('guidance.buyCardList', patient.buyCardList)
      this.$confirm('确定办理', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var reqDto = {
          guidanceCode: patient.guidanceCode,
          patientId: patient.id,
          payableAmountInfo: patient.payableAmountInfo,
          cardPayInfo: patient.cardPayInfo,
          drugPayInfo: patient.drugPayInfo,
        }
        console.log('paid reqDto', reqDto)
        const addPaidRes = await addPaid(reqDto)
        console.log('addPaidRes', addPaidRes)

        this.$message({
          type: 'success',
          message: '办理成功!'
        });
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    checkDrugPaid(patient) {
      if (Number(patient.payableAmountInfo.payableDrugAmount) != Number(patient.drugPayInfo.planPaidDrugAmount)) {
        this.$alert('商品金额输入有误', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return false
      }
      if(Number(patient.drugPayInfo.freeAmount) != 0 && (!patient.drugPayInfo.remark || patient.drugPayInfo.remark.trim() == '')) {
        this.$alert('免费金额必须填写原因', '错误', {
          confirmButtonText: '确定',
          type: 'error',
        });
        return false
      }
      return true
    },
    changeStartDate(row) {
      console.log('row', row)
      if(row.type == 2) {
        if(!row.startDate) {
          this.$set(row, 'startDateStr', undefined)
          row.visible = false
          return
        }
        const rule = JSON.parse(row.rule)
        const endDate = addDate(row.startDate, 'day', Number(rule.limitDays))
        rule.endTime = endDate
        this.$set(row, 'startDateStr', dateToString(row.startDate, 1).substring(2) + ' - ' + dateToString(endDate, 1).substring(2))
        row.visible = false
      }
    },
    inputPaidDrugAmount(patient) {
      let drugPayInfo = patient.drugPayInfo
      this.checkNumInput(drugPayInfo, 'storedCardAmount', drugPayInfo.storedCardAmount)
      // 使用前后卡余额
      if (drugPayInfo.patientCardId) {
        const patientCard =  this.patientCardEnum.find(card => card.id === drugPayInfo.patientCardId)
        this.calculateCardAfterAmount(patientCard, patient)
      }
      this.checkNumInput(drugPayInfo, 'cashAmount', drugPayInfo.cashAmount)
      this.checkNumInput(drugPayInfo, 'wechatAmount', drugPayInfo.wechatAmount)
      this.checkNumInput(drugPayInfo, 'alipayAmount', drugPayInfo.alipayAmount)
      this.checkNumInput(drugPayInfo, 'outCardAmount', drugPayInfo.outCardAmount)
      this.checkNumInput(drugPayInfo, 'debtAmount', drugPayInfo.debtAmount)
      this.checkNumInput(drugPayInfo, 'freeAmount', drugPayInfo.freeAmount)
      const planPaidTotalAmount = new Decimal(drugPayInfo.cashAmount).plus(new Decimal(drugPayInfo.storedCardAmount)).plus(new Decimal(drugPayInfo.wechatAmount)).plus(new Decimal(drugPayInfo.alipayAmount)).plus(new Decimal(drugPayInfo.outCardAmount)).plus(new Decimal(drugPayInfo.debtAmount)).plus(new Decimal(drugPayInfo.freeAmount))
      const realPaidTotalAmount = new Decimal(drugPayInfo.cashAmount).plus(new Decimal(drugPayInfo.storedCardAmount)).plus(new Decimal(drugPayInfo.wechatAmount)).plus(new Decimal(drugPayInfo.alipayAmount)).plus(new Decimal(drugPayInfo.outCardAmount))
      console.log(realPaidTotalAmount.toNumber())
      this.$set(drugPayInfo, 'planPaidDrugAmount', planPaidTotalAmount.toNumber())
      this.$set(drugPayInfo, 'realPaidDrugAmount', realPaidTotalAmount.toNumber())
      this.calculateDrugDiffAmount(patient)
    },
    calculateDrugDiffAmount(patient) {
      let drugPayInfo = patient.drugPayInfo
      // 计算应付款与已付款的差
      this.$set(drugPayInfo, 'differDrugAmount', '')
      const payableDrugAmount = new Decimal(patient.payableAmountInfo.payableDrugAmount)
      const planPaidDrugAmount = new Decimal(patient.drugPayInfo.planPaidDrugAmount)
      const absDifAmount = Math.abs(payableDrugAmount.sub(planPaidDrugAmount).toNumber())
      if(payableDrugAmount.comparedTo(planPaidDrugAmount) > 0) {
        this.$set(drugPayInfo, 'differDrugAmount', '(少' + absDifAmount + ')')
      } else if (payableDrugAmount.comparedTo(planPaidDrugAmount) < 0){
        this.$set(drugPayInfo, 'differDrugAmount', '(多' + absDifAmount + ')')
      }
    },
    inputPaidCardAmount(patient) {
      var cardPayInfo = patient.cardPayInfo
      this.checkNumInput(cardPayInfo, 'cashAmount', cardPayInfo.cashAmount)
      this.checkNumInput(cardPayInfo, 'wechatAmount', cardPayInfo.wechatAmount)
      this.checkNumInput(cardPayInfo, 'alipayAmount', cardPayInfo.alipayAmount)
      this.checkNumInput(cardPayInfo, 'outCardAmount', cardPayInfo.outCardAmount)
      this.checkNumInput(cardPayInfo, 'debtAmount', cardPayInfo.debtAmount)
      this.checkNumInput(cardPayInfo, 'freeAmount', cardPayInfo.freeAmount)
      const planPaidTotalAmount = new Decimal(cardPayInfo.cashAmount).plus(new Decimal(cardPayInfo.wechatAmount)).plus(new Decimal(cardPayInfo.alipayAmount)).plus(new Decimal(cardPayInfo.outCardAmount)).plus(new Decimal(cardPayInfo.debtAmount)).plus(new Decimal(cardPayInfo.freeAmount))
      const realPaidTotalAmount = new Decimal(cardPayInfo.cashAmount).plus(new Decimal(cardPayInfo.wechatAmount)).plus(new Decimal(cardPayInfo.alipayAmount)).plus(new Decimal(cardPayInfo.outCardAmount))
      this.$set(cardPayInfo, 'planPaidCardAmount', planPaidTotalAmount.toNumber())
      this.$set(cardPayInfo, 'realPaidCardAmount', realPaidTotalAmount.toNumber())
      this.calculateCardDiffAmount(patient)
    },
    calculateCardDiffAmount(patient) {
      var cardPayInfo = patient.cardPayInfo
      // 计算应付款与已付款的差
      this.$set(cardPayInfo, 'differCardAmount', '')
      const payableCardAmount = new Decimal(patient.payableAmountInfo.payableCardAmount)
      const planPaidCardAmount = new Decimal(patient.cardPayInfo.planPaidCardAmount)
      const absDifAmount = Math.abs(payableCardAmount.sub(planPaidCardAmount).toNumber())
      if(payableCardAmount.comparedTo(planPaidCardAmount) > 0) {
        this.$set(cardPayInfo, 'differCardAmount', '(少' + absDifAmount + ')')
      } else if (payableCardAmount.comparedTo(planPaidCardAmount) < 0){
        this.$set(cardPayInfo, 'differCardAmount', '(多' + absDifAmount + ')')
      }
    },
    checkNumInput(obj, prop, content) {
      // 判空
      if(!content) this.$set(obj, prop, 0)
      // 删除0开头
      this.$set(obj, prop, Number(content))
      // 负数时改为0
      if(!content) this.$set(obj, prop, 0)
    },
    calculateCardAfterAmount(patientCard, patient) {
      let drugPayInfo = patient.drugPayInfo
      let beforeAmount = patientCard.balance
      let storedCardAmount = new Decimal(drugPayInfo.storedCardAmount)
      let afterAmount = new Decimal(beforeAmount).sub(storedCardAmount).toNumber()
      // 余额不足
      if(Number(afterAmount < 0)) {
        this.$set(drugPayInfo, 'storedCardAmount' , patientCard.balance)
        this.$set(drugPayInfo, 'afterAmount' , 0)
        // 计算自费与优惠金额
        this.calculateStoredCardFreeAmount(patientCard, drugPayInfo)
        this.$message.error('储值卡余额不足')
        return
      }
      this.$set(drugPayInfo, 'beforeAmount' , beforeAmount)
      this.$set(drugPayInfo, 'afterAmount' , afterAmount)
      // 计算自费与优惠金额
      this.calculateStoredCardFreeAmount(patientCard, drugPayInfo)
    },
    calculateStoredCardFreeAmount(patientCard, drugPayInfo) {
      const storedCardAmount = new Decimal(drugPayInfo.storedCardAmount)
      const amount = JSON.parse(patientCard.cardRule).amount
      const giveaway = JSON.parse(patientCard.cardRule).giveaway
      // rate = 赠金 / 本金+赠金
      // 免费金额 = storedCardAmount * rate
      const freeAmount = storedCardAmount.mul(new Decimal(giveaway)).div(new Decimal(amount).add(new Decimal(giveaway))).toNumber().toFixed(2)
      this.$set(drugPayInfo, 'storedCardFreeAmount' , freeAmount)
      this.$set(drugPayInfo, 'storedCardPatientAmount' , storedCardAmount.sub(new Decimal(freeAmount)).toNumber())
    },
    selectPatientCard(patientCard, patient) {
      // 选择卡后，清空储值卡扣减金额
      let drugPayInfo = patient.drugPayInfo
      if(new Decimal(drugPayInfo.storedCardAmount).comparedTo(new Decimal(patientCard.balance)) >= 0) {
        this.$set(drugPayInfo, 'storedCardAmount' , patientCard.balance)
      }
      this.calculateCardAfterAmount(patientCard, patient)
      this.$set(drugPayInfo, 'storedCardDisabled' , false)
    },
    payableInfoDialog(patient) {
      this.dialogPayableInfo = patient.payableAmountInfo
      console.log('dialogPayableInfo', this.dialogPayableInfo)
      this.payableInfoVisible = true
    },
    cancelInfo() {
      this.payableInfoVisible = false
    }
  },
}
</script>

<style lang="scss" scoped>
  .del-btn {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 4px;
  }
  .activity-box {
    display: flex;
    justify-content: space-around;
  }

  .first-row {
    position: absolute;
    top: 8px;
    left: 3px;
    width: 93%;
  }
  
  .second-row {
    position: absolute;
    top: 38px;
    left: 3px;
    width: 93%;
  }
  table {
      border-collapse: collapse;
      margin: 20px 0;
      font-family: Arial, sans-serif;
  }
  th, td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: center;
  }
  th {
      background-color: #f2f2f2;
      font-weight: bold;
  }

  
  .repair-box ::v-deep .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 93%;
    margin: 0 0
  }

  ::v-deep .el-tabs__item {
    height: 30px;
    line-height: 30px;
  }
  .app-container > ::v-deep .el-tabs--border-card > .el-tabs__header{
    position: fixed;
    z-index: 98;
    top: 84px;
  }

  .el-main > .patient-base-info > .el-collapse {
    position: fixed;
    z-index: 98;
    top: 160px;
    width: 72%
  }
  .el-main > ::v-deep .el-tabs--border-card {
    margin-top: 70px;
  }
  .patient-base-info {
    position: fixed;
    z-index: 97;
    background-color: #fff;
    width: 72%;
    padding: 0 16px;
  }
  .table-separate {
    opacity: 0;border: none
    th {
      opacity: 0;border: none
    }
  }

  .drug-payment-cell-1 {
    width: 90px;
  }
  .drug-payment-cell-2 {
    width: 200px;
  }
  .drug-payment-cell-3 {
    width: 140px;
  }
  .drug-payment-cell-4 {
    width: 250px;
  }
  .drug-payment-cell-5 {
    width: 120px;
  }
  .drug-payment-cell-6 {
    width: 200px;
  }
  .card-payment-description {
    font-size: 12px;
    min-height: 18px;
    line-height: 18px;
    padding: 5;
    text-align: left;
  }

</style>